<?php
/**
 * Controller pre ftp uzivatela
 * @author Tomas Srna
 * @package bakalarka
 */

class HostingFtpController extends HostingAbstractController
{
	protected $resource = 'hosting:*';
	
	/**
	 * V tomto controlleri musime mat vybratu domenu
	 * a ked mame id, musi byt nas zaznam
	 */
	public function preDispatch()
	{
		parent::preDispatch();
			
		if(!property_exists($this, 'hosting'))
		{
			throw new Exception('L::errorObjectNotFound;'.
				json_encode(array('HostingFtpModel(?)')));
		}
		
		if(array_key_exists('id', $_GET))
		{
			$hosting_id = Selector::select('id')
				->from(HostingModel::struct())
				->where('name = ?', $this->hosting)
				->fetch()->current()->id;
			
			$test = HostingFtpModel::load(array('id' => $_GET['id']));
			
			if($test && $test->hosting_id != $hosting_id)
				throw new PermissionDeniedException('L::badContext;'.
					json_encode(array('HostingFtpModel('.$_GET['id'].')')
				), 'HostingFtpModel('.$_GET['id'].')');
		}
	}
	
	/**
	 * Index
	 */
	public function index()
	{
		$t = Template::instance();
		
		$t->plusmenu = $this->plusmenu;
		$t->plusmenu_title =$this->plusmenu_title;
		
		$dv = new DynamicView();
		$dv->buttonAdd = true;
		$dv->primaryKeys = array('id');
		$dv->baseUrl = APPBASE."hosting/{$this->hosting}/ftp";
		
		$dv->itemCount = Selector::select("count(*) as c")
			->from(HostingFtpModel::struct())
			->where('hosting_id = (?)', new Expression(
				Selector::select('id')->from(HostingModel::struct())
					->where('name = ?', $this->hosting)
			))->fetch()->current()->c;
			
		$t->dv = $dv;
		$t->dvw = new DynamicViewWriter($t->dv, $t);
		
		$t->title = L::selected()->ftp;
		
		$hosting = Selector::select()->from(HostingModel::struct())
					->where('name = ?', $this->hosting)->fetch()
					->current();
		
		$t->text = "";
		$t->text .= '<p><strong>'.L::selected()->usedSpace.'</strong> ';
		$t->text .= new ProgressbarWriter($hosting->used, 
							$hosting->space, new SpaceWriter());
		$t->text .= '</p>';
		
		
		$t->text .= '<p>'.sprintf(L::selected()->ftpHowto, 
			Config::$ftpAddress).'</p>';
		
		$t->render('dynamic-view');
	}

	/**
	 * Data
	 */
	public function data()
	{
		$params = $_GET;
		
		$t = Template::instance();
		
		// Kontrola vstupov
		$by_possible = array("id", "username", "root", "accessed");
		
		$dt = new DynamicTable();
		$dt->primaryKeys = array('id');
		$dt->itemCount = Selector::select("count(*) as c")
			->from(HostingFtpModel::struct())
			->where('hosting_id = (?)', new Expression(
				Selector::select('id')->from(HostingModel::struct())
					->where('name = ?', $this->hosting)
			))->fetch()->current()->c;
		
		$dt->buttons = array(
			new Button('pencil.png', L::selected()->edit, 
				"act('edit', false, %params%)"),
			new Button('key.png', L::selected()->passwd, 
				"act('passwd', false, %params%)"),
			new Button('delete.png', L::selected()->delete, 
				"act('delete', true, %params%)"),
		);
		
		if(!$dt->check($params, $by_possible))
			$t->error = L::selected()->invalidInput;
			
		if(!property_exists($t, 'error'))
		{
			$dt->headers['id'] = L::selected()->id;
			$dt->headers['username'] = L::selected()->username;
			$dt->headers['root'] = L::selected()->root;
			$dt->headers['accessed'] = L::selected()->accessed;
			
			if(!array_key_exists('page', $params))
				$params['page'] = 1;
			
			$select = Selector::select()
						->from(HostingFtpModel::struct())
						->where('hosting_id = (?)', new Expression(
							Selector::select('id')->from(
								HostingModel::struct())
								->where('name = ?', $this->hosting)))
						->page($params['page'])
						->by($params);
			
			$dt->data = $select->fetch();
			
			$t->dtw = new DynamicTableWriter($dt, $t);
		}
		
		$t->dt = $dt;
		$t->render('dynamic-table');
	}

	/**
	 * Edit
	 * @param bool $create		Vytvarame novy objekt?
	 */
	public function edit($create = false)
	{
		$t = Template::instance();
		
		$t->hosting = $this->hosting;
		
		$t->plusmenu = $this->plusmenu;
		$t->plusmenu_title =$this->plusmenu_title;
		
		if($create)
		{
			$t->title = L::selected()->createFtp;
			
			$_POST['updated'] = new Expression('NOW');
			
			$hosting_id = Selector::select('id')
				->from(HostingModel::struct())
				->where('name = ?', $this->hosting)
				->fetch()->current()->id;
			$_POST['hosting_id'] = $hosting_id; 
			
			if(getenv('REQUEST_METHOD') == 'POST')
				$model = HostingFtpModel::create($_POST);
			else
				$model = NULL;
		}
		else
		{
			$t->title = L::selected()->editFtp;
			
			// Skontrolujeme ci existuje objekt a nacitame ho
			if(	!array_key_exists('id', $_GET))
				throw new Exception('L::errorObjectNotFound;'.
						json_encode(array('HostingFtpModel(?)')));
						
			$model = HostingFtpModel::load(array(
						'id' => $_GET['id']
					));
			if(!$model)
				throw new Exception('L::errorObjectNotFound;'.
					json_encode(array(sprintf('HostingFtpModel(%s)',
					$_GET['id']))));
		}
		
		if(getenv('REQUEST_METHOD') == 'POST')
		{
			$f = new HostingFtpForm(&$t, $_POST);
			$f->hosting = $this->hosting;
			
			if($f->validate())
			{
				// Kontrola duplicity
				if($create)
				{
					$c = Selector::select('count(*) as c')
							->from(HostingFtpModel::struct())
							->where('username = ?', 
								$_POST['username'])
							->fetch()->current()->c;

					if($c > 0)
						$dup = true;
					else
						$dup = NULL;
				}
				
				if(!$create || $dup == NULL)
				{
					$model->set($_POST);
					
					// Pridame dalsie povinne veci
					$model->updated = new Expression('NOW()');
					
					$model->save();
					
					if($create)
						Logger::log('L::objectCreated_s;'.
							json_encode((string)$model), 'info');
					else
						Logger::log('L::objectChanged_s;'.
							json_encode((string)$model), 'info');
					$this->autoredir();
				}
				else
					$t->error = L::selected()->duplicity;
			}
			else
				$t->error = L::selected()->invalidForm;
		}
		else
		{
			$f = new HostingFtpForm(&$t, $model);
			$f->hosting = $this->hosting;
		}
		
		$fw = new FormWriter($f);
		$t->fw = $fw;
		
		$t->render('form');
	}
	

	/**
	 * Vytvorenie noveho zaznamu
	 * 
	 */
	public function create()
	{
		// Zavolame edit s $create = true
		return $this->edit(true);
	}
	
	/**
	 * Odstranenie riadka
	 */
	public function delete()
	{
		// Skontrolujeme ci existuje objekt a nacitame ho
		if(	!array_key_exists('id', $_GET))
			throw new Exception('L::errorObjectNotFound;'.
					json_encode(array('HostingFtpModel(?)')));
					
		$model = HostingFtpModel::load(array(
			'id' => $_GET['id'],
		));
		
		if(!$model)
			throw new Exception('L::errorObjectNotFound;'.
				json_encode(array(sprintf('HostingFtpModel(%s)', 
				$_GET['id']))));
				
		// Zmazeme vsetky zavislosti
		// -- ziadne
		
		// Zmazeme samotny riadok
		$model->delete();
		
		// Zalogujeme
		Logger::log('L::objectDeleted_s;'.
			json_encode((string)$model), 'info');
		
		$this->autoredir();
	}
	
	/**
	 * Zmena hesla
	 */
	public function passwd()
	{
		$t = Template::instance();
		$t->title = L::selected()->passwordChange;
					
		// Skontrolujeme ci existuje objekt a nacitame ho
		if(!array_key_exists('id', $_GET))
			throw new Exception('L::errorObjectNotFound;'.
					json_encode(array('HostingFtpModel(?)')));
					
		$model = HostingFtpModel::load(array('id' => $_GET['id']));
		if(!$model)
			throw new Exception('L::errorObjectNotFound;'.
				json_encode(array(sprintf('HostingFtpModel(%s)', $_GET['id']))));
		
		if(getenv('REQUEST_METHOD') == 'POST')
		{
			$f = new PasswdForm($t, $_POST);
			
			if($f->validate())
			{
				// ProFTPd pouziva MD5
				$model->password_hash = hash(Config::$hash_function_ftp, 
					$_POST['password']);
				
				$model->save();
				Logger::log('L::objectChanged_s;'.
					json_encode((string)$model), 'info');
				
				$this->autoredir();
			}
			else
				$t->error = L::selected()->invalidForm;
		}
		else
		{
			$f = new PasswdForm($t, $model);
		}
		
		$fw = new FormWriter($f);
		
		$t->fw = $fw;
		
		$t->render('form');
	}

}
	